package com.easytake.emotioncat.util;

import com.alibaba.fastjson2.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WxCacheUtil {

    //todo 获取要更换Map防止内存溢出http://www.tuohang.net/article/245156.html
    private static final Map<String, String> openIdSessionKeyMap = new ConcurrentHashMap<>();

    public static String addCache(String code, String openId, String sessionKey) {
        String token = UuidUtil.getUUID();
        AuthInfo authInfo = new AuthInfo(token, openId, sessionKey, System.currentTimeMillis(), code);
        openIdSessionKeyMap.put(token, JSON.toJSONString(authInfo));
        return token;
    }

    public static String getOpenId(String token) {
        if (!StringUtils.hasText(token)) {
            return null;
        }
        String cacheVal = openIdSessionKeyMap.get(token);
        if (StringUtils.hasText(cacheVal)) {
            AuthInfo authInfo = JSON.parseObject(cacheVal, AuthInfo.class);
            return authInfo.getOpenId();
        }
        return null;
    }

    public static void clearToken(String token) {
        openIdSessionKeyMap.remove(token);
    }

    /**
     * http header中拿到token，根据token从缓存中拿到登录用户信息
     *
     * @return wx用户标识
     */
    public static String getOpenId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("token");
        return getOpenId(token);
    }

    @Data
    @AllArgsConstructor
    static class AuthInfo {
        String token;
        String openId;
        String sessionKey;
        Long timeStamp;
        String code;
    }
}
